﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HanGu.Entity;
using HanGu.Services.Interface;
using System.IO;
using HanGu.Common;

namespace Hangu.WebClient.Common
{
    public class DelTempFile
    {
        private DelTempFile()
        { }
        public static readonly DelTempFile Instance = new DelTempFile();
        private static readonly IFileManage serviceFile = ServiceFactory.GetService<IFileManage>();
        private const int delTime = 30;//删除30分钟之前的文件
        public void DelFile()
        {
            try
            {
                object lock_ = new object();
                lock (lock_)
                {
                    #region 删除30分之前数据库的临时文件
                    List<FileManage> groupFiles = serviceFile.GetAll();
                    if (groupFiles != null)
                    {
                        foreach (var item in groupFiles)//删除文件
                        {
                            if (item.FilePath.IndexOf("Temp/") > 0 && item.UploadTime.AddMinutes(delTime) <= DateTime.Now)
                            {
                                try
                                {
                                    using (UploadFileManage uploadFile = new UploadFileManage())
                                    {
                                        uploadFile.DeleteFile(item.FilePath);
                                    }
                                    serviceFile.DeleteByID(item.ID);
                                }
                                catch
                                { }
                            }
                        }

                    }
                    #endregion

                    #region 删除临时文件夹的文件
                    string[] directorys = Directory.GetDirectories(System.Web.HttpContext.Current.Server.MapPath("~/Upload/Temp"));
                    foreach (string item in directorys)
                    {
                        if (File.GetLastWriteTime(item).AddMinutes(delTime) <= DateTime.Now)
                        {
                            if (Directory.Exists(item))
                            {
                                Directory.Delete(item, true);
                            }
                        }
                    }
                    #endregion

                }
            }
            catch
            { }
        }
    }


}